package com.lukebang.service.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lukebang.constant.Const;
import com.lukebang.constant.CurtainType;
import com.lukebang.dao.CityCostRuleDAO;
import com.lukebang.dao.CustomerAddressDAO;
import com.lukebang.dao.GoodDAO;
import com.lukebang.dao.GoodSpecialDAO;
import com.lukebang.dao.IndentDao;
import com.lukebang.dao.InstallIndentDAO;
import com.lukebang.dao.MeasureIndentDAO;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.dao.PictureDAO;
import com.lukebang.dao.RepairIndentDAO;
import com.lukebang.dao.TerritoryDAO;
import com.lukebang.dao.WorkerDao;
import com.lukebang.dao.WorkerWalletRecordDao;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.CustomerAddress;
import com.lukebang.pojo.Good;
import com.lukebang.pojo.GoodSpecial;
import com.lukebang.pojo.Indent;
import com.lukebang.pojo.InstallIndent;
import com.lukebang.pojo.Merchant;
import com.lukebang.service.IGoodService;
import com.lukebang.service.IInstallIndentService;
import com.lukebang.util.DateUtils;
import com.lukebang.util.ClothCurtain.Arith;
import com.lukebang.util.redis.JedisPoolUtils;
import redis.clients.jedis.Jedis;

/**
 * 
 * InstallIndentServiceImpl 上午11:16:02
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("installIndentSER")
public class InstallIndentServiceImpl implements IInstallIndentService {

	@Resource
	CustomerAddressDAO customerAddressDAO;
	@Resource
	TerritoryDAO territoryDAO;
	@Resource
	IndentDao indentDao;
	@Resource
	InstallIndentDAO installIndentDAO;
	@Resource
	MeasureIndentDAO measureIndentDAO;
	@Resource
	RepairIndentDAO repairIndentDAO;
	@Resource
	CityCostRuleDAO cityCostRuleDAO;
	@Resource
	GoodDAO goodDAO;
	@Resource
	GoodSpecialDAO goodSpecialDAO;
	@Autowired
	IGoodService goodsService;
	@Resource
	PictureDAO pictureDAO;
	@Resource
	private MerchantDAO merchantDAO;
	@Resource
	private MerchantsWalletRecordDAO merchantsWalletRecordDAO;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private WorkerWalletRecordDao workerWalletRecordDao;

	/**
	 * 计算刚插入的安装订单的各个价格 xiaGuanghui 2017年6月9日 上午9:38:47
	 * 
	 * @param indentId
	 */
	private Map<String, Object> calculateIndentByIndentId(Indent indent, String city,
			CityCostRule cityCostRuleForMerchant, CityCostRule cityCostRuleForWorker) {
		Map<String, Object> paramMap = new HashMap<>();
		Double merchantsPrice = 0.00;
		Double indentPrice = 0.00;
		// 获取订单的id
		Integer indentId = indent.getIndentId();
		List<Good> goodsList = goodDAO.selectAllIndentGoodByIndent(indentId);
		if (null != goodsList && goodsList.size() > 0) {
			// 计算订单旗下的所有goods的货物价格
			for (int a = 0; a < goodsList.size(); a++) {
				Good good = goodsList.get(a);
				if (good == null)
					continue;
				Map<String, Object> map = goodsService.calculateInstallIndent(good, city);
				merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
				indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
			}
		}
		paramMap.put("indentPrice", indentPrice);
		paramMap.put("merchantsPrice", merchantsPrice);
		paramMap.put("merchantsRealPrice", merchantsPrice);
		paramMap.put("workerRealPrice", indentPrice);
		return paramMap;
	}

	/**
	 * 绑定goods和indent到表格goods_indent xiaGuanghui 2017年6月7日 下午6:18:27
	 * 
	 * @param indentId
	 * @param good
	 */
	public void insertBindingGoodsWithIndent(Integer indentId, Good good) {
		Map<String, Object> param = new HashMap<>();
		param.put("indentId", indentId);
		param.put("goodsId", good.getGoodsId());
		installIndentDAO.insertGoodsIndent(param);
	}

	/**
	 * 为goods添加窗帘尺寸,添加的窗帘尺寸如果是成品帘就不会再是布艺帘,反之成立 xiaGuanghui 2017年6月7日 下午4:07:19
	 * 
	 * @param indentId
	 *            对应的indentId
	 * @param goodsId
	 *            对应的goodsId
	 * @param finishShade
	 *            成品帘的尺寸
	 * @param clothShade
	 *            布艺帘的尺寸
	 * @param yarnShade
	 *            纱的尺寸
	 * @param headShade
	 *            帘头的尺寸
	 */
	public void insertSpecial(Integer indentId, Good good, String finishShade, String clothShade, String yarnShade,
			String headShade) {
		// 获取good的一些属性
		Integer goodsId = good.getGoodsId();// goodsId
		Integer installCase = good.getInstallCase();// 布纱是否安装一致
		// 添加成品帘
		if (good.getType() == 1) { // 成品帘
			JSONArray jsonArray = JSONArray.parseArray(finishShade);
			for (int index = 0; index < jsonArray.size(); index++) {
				JSONObject finishShadeJsonObject = jsonArray.getJSONObject(index);
				inserJsonObject(index, 3, goodsId, installCase, finishShadeJsonObject,
						CurtainType.ProductCurtain.getIndex());
			}
		} else { // 添加布艺帘
			if (clothShade != null) {
				JSONArray jsonArray = JSONArray.parseArray(clothShade);
				for (int index = 0; index < jsonArray.size(); index++) {
					JSONObject clothShadeJsonObject = jsonArray.getJSONObject(index);
					inserJsonObject(index, 0, goodsId, installCase, clothShadeJsonObject,
							CurtainType.ClothCurtanin.getIndex());
				}
			}
			if (yarnShade != null) {
				JSONArray jsonArray = JSONArray.parseArray(yarnShade);
				for (int index = 0; index < jsonArray.size(); index++) {
					JSONObject yarnShadeJsonObject = jsonArray.getJSONObject(index);
					inserJsonObject(index, 1, goodsId, installCase, yarnShadeJsonObject,
							CurtainType.ClothCurtanin.getIndex());
				}
			}
			if (headShade != null) {
				JSONArray jsonArray = JSONArray.parseArray(headShade);
				for (int index = 0; index < jsonArray.size(); index++) {
					JSONObject headShadeJsonObject = jsonArray.getJSONObject(index);
					inserJsonObject(index, 2, goodsId, installCase, headShadeJsonObject,
							CurtainType.ClothCurtanin.getIndex());
				}
			}
		}

	}

	/**
	 * 插入special到数据库 xiaGuanghui 2017年6月7日 下午4:56:10
	 * 
	 * @param specialType
	 *            对应数据库goods_special的字段type的值(0布 1纱 2帘头 3成品帘')
	 * @param goodsId
	 * @param installCase(适用枚举进行赋值)
	 *            ClothCurtanin("布艺帘", 1), ProductCurtain("成品帘", 2);
	 * @param curtainType(1代表布
	 *            2代表成品帘)
	 */
	public void inserJsonObject(int index, int specialType, Integer goodsId, Integer installCase, JSONObject jsonObject,
			int curtainType) {
		Good specialGood = new Good();
		if (specialType != 2)
			specialGood.setPinstallSite(jsonObject.getString("pinstallSite"));
		if (curtainType == CurtainType.ClothCurtanin.getIndex()) {// 代表布艺帘
			specialGood.setAccessoriesType(jsonObject.getString("accessoriesType"));
			specialGood.setSaleNumber(jsonObject.getDouble("saleNumber"));
			specialGood.setAcc(null == jsonObject.getString("acc") ? "无配件配饰" : jsonObject.getString("acc"));
			if (specialType == 0 || specialType == 1) {
				// number的值如果是布纱安装一致等于2否则等于1
				specialGood.setNumber(specialType == 0 ? (installCase != null && installCase != 0 ? 2 : 1) : 1);
				specialGood.setPanzhuangfangshi(jsonObject.getString("panzhuangfangshi"));
			}
			// 如果布纱双层 并且布纱位置安装一致的话
			if (installCase != null && installCase == 1) {
				// 为纱尺寸添加一个配件 但是没有对应的ACCID
				GoodSpecial goodSpecial = new GoodSpecial();
				goodSpecial.setInstallSite("暂无");
				goodSpecial.setAccessoriesType(jsonObject.getString("accessoriesType"));
				goodSpecial.setWindow("暂无");
				goodSpecial.setWide(jsonObject.getDouble("wide"));
				goodSpecial.setHigh(jsonObject.getDouble("high"));
				goodSpecial.setProduction(0);
				goodSpecial.setType(1);
				goodSpecial.setGoodsId(goodsId);// 和goodsId绑定
				int goodsIdChild = goodsId * 10 + index;
				goodSpecial.setGoodsIdChild(goodsIdChild);
				goodSpecial.setRemark(jsonObject.getString("remark"));
				goodSpecialDAO.insertGoodsSpecial(goodSpecial);
			}
			if (specialType == 2)
				specialGood.setParsOfPars(jsonObject.getString("parsOfPars"));
		}

		// 插入specialGood
		goodDAO.insertGoods(specialGood);
		GoodSpecial goodSpecial = new GoodSpecial();
		goodSpecial.setAccId(specialGood.getGoodsId());
		goodSpecial.setInstallSite("暂无");
		goodSpecial.setAccessoriesType(jsonObject.getString("accessoriesType"));
		goodSpecial.setWindow("暂无");
		goodSpecial.setWide(jsonObject.getDouble("wide"));
		goodSpecial.setHigh(jsonObject.getDouble("high"));
		goodSpecial.setProduction(0);
		goodSpecial.setType(specialType);
		goodSpecial.setGoodsId(goodsId);// 和goodsId绑定
		int goodsIdChild = goodsId * 10 + index;
		goodSpecial.setGoodsIdChild(goodsIdChild);
		goodSpecial.setRemark(jsonObject.getString("remark"));
		goodSpecialDAO.insertGoodsSpecial(goodSpecial);
		// if ("不满墙（无窗帘盒）".equals(jsonObject.getString("installSite"))) {
		// Picture picture = new Picture();
		// // num为图片地址
		// // 把图片存到图片表里
		// picture.setImg(jsonObject.getString("num"));
		// picture.setSpecialId(goodSpecial.getSpecialId());
		// picture.setPaizhaoType(0);
		// pictureDAO.insertPicture(picture);
		// }
	}

	@Override
	public Map<String, Object> selectInstallIndentByMerchant(HttpSession session, String cuName, String cuPhone,
			String indentID, String subscribeTimeBegin, String subscribeTimeEnd, String beginTimeBegin,
			String beginTimeEnd, Integer indentStatus, Integer offset, Integer limit, String sort, String order) {
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		Map<String, Object> retsMap = new HashMap<String, Object>();
		retsMap.put("total", 0);
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("offset", offset);
		queryMap.put("limit", limit);
		queryMap.put("sort", sort);
		queryMap.put("order", order);
		queryMap.put("customerName", cuName);
		queryMap.put("customerPhone", cuPhone);
		queryMap.put("indentID", indentID);
		queryMap.put("subscribeTimeBegin", subscribeTimeBegin);
		queryMap.put("subscribeTimeEnd", subscribeTimeEnd);
		queryMap.put("beginTimeBegin", beginTimeBegin);
		queryMap.put("beginTimeEnd", beginTimeEnd);
		queryMap.put("indentStatus", indentStatus);
		queryMap.put("merchantID", merchant.getMerchantsId());
		List<Indent> beans = installIndentDAO.selectInstallIndentByMerchant(queryMap);
		retsMap.put("total", installIndentDAO.selectInstallIndentCountByMerchant(queryMap));
		retsMap.put("rows", beans);
		return retsMap;
	}

	@Override
	public Map<String, Object> insertInstallIndent(HttpServletRequest request, String phone, String name, String remark,
			String installAddress, String province, String city, String country, String subscribeTime,
			Integer isNeedTakeGoods, String pickupPhone, String pickupProvince, String pickupCity, String pickupCountry,
			String pickAddress, String fakeIndentID, HttpSession session) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		// 添加订单基础信息
		// 得到登陆的商户的信息
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		// 根据传送过来的code 转化成对应的省和市和城镇

		// ====================先为用户添加一个订单地址
		CustomerAddress customerAddress = new CustomerAddress();
		customerAddress.setAddress(installAddress);
		List<String> areaNames = territoryDAO.selectForConvertCodeToAreaName(province, city, country);
		if (areaNames.size() > 0) {
			customerAddress.setProvince(areaNames.get(0));
			customerAddress.setCity(areaNames.get(1));
			customerAddress.setArea(areaNames.get(2));
		}
		customerAddress.setAreaCode(country);
		customerAddress.setName(name);
		customerAddress.setPhone(phone);
		customerAddress.setCuAddressCodeStr(province + "/" + city);
		customerAddressDAO.insertCustomerAddress(customerAddress);
		// ====================正式插入订单信息
		InstallIndent indent = new InstallIndent();
		// '订单类型0测量 1安装 2维修 3经销商自主测量的',
		indent.setType(1);
		indent.setStatus(4);
		// 是谁下的订单
		indent.setCustomerId(merchant.getMerchantsId());
		// 订单产生时间
		indent.setBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		// 订单预约的时间
		indent.setSubscribeTime(subscribeTime);
		// 代表是商家或者个人下的订单 有利于后面的统计
		indent.setIndentType(3);
		indent.setCuAdId(customerAddress.getCuAdId());
		if (isNeedTakeGoods == 1) {
			// 设置取货地址
			List<String> pickupAreaNames = territoryDAO.selectForConvertCodeToAreaName(province, city, country);
			indent.setBaseAddress(pickupAreaNames.get(0) + pickupAreaNames.get(1) + pickupAreaNames.get(2));
			indent.setDetailAddress(pickAddress);
			indent.setTakeGoodsTel(pickupPhone);
		}
		indent.setRemark(remark);
		indent.setIsNeedTakeGoods(isNeedTakeGoods);
		indent.setIndentSource(1);

		// 插入该订单
		installIndentDAO.insertInstallIndent(indent);

		if ("1".equals(request.getAttribute("toInstall"))) {
			List<Good> list = goodDAO.selectInstallIndentGoodByIndent(fakeIndentID);
			if (list != null && list.size() > 0) {
				for (Good good : list) {
					// 插入当前good的基本信息
					// 绑定订单id和goods
					insertBindingGoodsWithIndent(indent.getIndentId(), good);
				}
			}
		} else {
			// 连接reDis
			Jedis jedis = JedisPoolUtils.getJedis();
			jedis.select(2);
			// 存放当前Good的基本信息
			List<String> lrange = jedis.lrange(fakeIndentID, 0, -1);
			for (String fakeGoodID : lrange) {
				String goodMapStr = jedis.get(fakeIndentID + "_" + fakeGoodID);
				JSONObject goodMapJSON = JSON.parseObject(goodMapStr);
				String finishShade = goodMapJSON.get("finishShade") == null ? null
						: goodMapJSON.get("finishShade").toString();
				String clothShade = goodMapJSON.get("clothShade") == null ? null
						: goodMapJSON.get("clothShade").toString();
				String yarnShade = goodMapJSON.get("yarnShade") == null ? null
						: goodMapJSON.get("yarnShade").toString();
				String headShade = goodMapJSON.get("headShade") == null ? null
						: goodMapJSON.get("headShade").toString();
				Good good = JSON.parseObject(goodMapJSON.get("currentGood").toString(), Good.class);

				if (good != null) {
					// 打印参数日志
					// good的istianxie=1表示本次为good添加尺寸
					good.setIstianxie(1);
					good.setShadeHead((headShade == null || "".equals(headShade)) ? 0 : 1);
					good.setShadingCloth(0);
					good.setWindow("暂无");
					good.setOtherRoom("暂无");
					// 插入当前good的基本信息
					goodDAO.insertGoods(good);
					// 插入special信息
					insertSpecial(indent.getIndentId(), good, finishShade, clothShade, yarnShade, headShade);
					// 绑定订单id和goods
					insertBindingGoodsWithIndent(indent.getIndentId(), good);
				}
			}
			JedisPoolUtils.close(jedis);
		}

		// 计算商家和工人对应的配件价格
		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
		CityCostRule cityCostRuleForWorker = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
		// 返回值包括 indentPrice merchantsPrice realPrice
		Map<String, Object> priceMap = calculateIndentByIndentId(indent, customerAddress.getCuAddressCodeStr(),
				cityCostRuleForMerchant, cityCostRuleForWorker);
		if (priceMap != null) {
			Double merchantsPrice = Double.valueOf(priceMap.get("merchantsPrice").toString());
			Double indentPrice = Double.valueOf(priceMap.get("indentPrice").toString());
			Double merchantsRealPrice = Double.valueOf(priceMap.get("merchantsRealPrice").toString());
			Double workerRealPrice = Double.valueOf(priceMap.get("workerRealPrice").toString());
			if (cityCostRuleForMerchant != null && cityCostRuleForWorker != null) {
				if (merchantsRealPrice.compareTo(cityCostRuleForMerchant.getInstallStartingFare()) >= 0) {
					merchantsPrice = merchantsRealPrice;
				} else {
					merchantsPrice = cityCostRuleForMerchant.getInstallStartingFare();
				}

				if (workerRealPrice.compareTo(cityCostRuleForWorker.getInstallStartingFare()) <= 0) {
					indentPrice = cityCostRuleForWorker.getInstallStartingFare();
				}
				// 是否需要添加取货地址
				if (isNeedTakeGoods == 1) {
					merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsPrice);
					indentPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), indentPrice);
					workerRealPrice=Arith.add((Double) cityCostRuleForWorker.getTakeGoodsPrice(), workerRealPrice);
					merchantsRealPrice=Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsRealPrice);
				}
			}
			priceMap.put("indentPrice", indentPrice);
			priceMap.put("merchantsPrice", merchantsPrice);
			priceMap.put("workerRealPrice", workerRealPrice);
			priceMap.put("merchantsRealPrice", merchantsRealPrice);
			priceMap.put("indentId", indent.getIndentId());
			installIndentDAO.modifyIndentByIndentId(priceMap);

			retMap.put("indentID", indent.getIndentId());
			retMap.put("price", merchantsPrice);
			retMap.put("workerRealPrice", workerRealPrice);
			retMap.put("merchantsRealPrice", merchantsRealPrice);
		}
		return retMap;
	}

//	@Override
//	public boolean modifyForPayInstallIndent(HttpServletRequest request, Integer indentID, Double addPrice,
//			Integer relievedBao, Integer crampetNumber, Integer fourClawNumber, Integer motorNumber, Double totalPrice,
//			HttpSession session) {
//		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
//		InstallIndent installIndent = installIndentDAO.selectByPrimaryKey(indentID);
//		if(installIndent==null)return false;
//		installIndent.setBigouNum(crampetNumber==null ?0:crampetNumber);
//		installIndent.setSizhuagouNum(fourClawNumber==null ?0:fourClawNumber);
//		installIndent.setMotorNum(motorNumber==null ?0:motorNumber);
//		/**
//		 * 查询出商人和工人不同的订花费规则
//		 */
//		CustomerAddress customerAddress = customerAddressDAO.selectCustomerAddressByIndent(indentID);
//		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
//				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
//		CityCostRule cityCostRuleForWorker = cityCostRuleDAO
//				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
//		// 计算商家和工人对应的配件价格
//		Double accessoryPriceForMerchant = cityCostRuleForMerchant.getCrampetPrice() * crampetNumber
//				+ cityCostRuleForMerchant.getFourClawPrice() * fourClawNumber
//				+ cityCostRuleForMerchant.getMotorPrice() * motorNumber;
//		Double accessoryPriceForWorker = cityCostRuleForWorker.getCrampetPrice() * crampetNumber
//				+ cityCostRuleForWorker.getFourClawPrice() * fourClawNumber
//				+ cityCostRuleForWorker.getMotorPrice() * motorNumber;
//		// 返回值包括 indentPrice merchantsPrice realPrice
//		Map<String, Object> priceMap = calculateIndentByIndentId(installIndent, customerAddress.getCuAddressCodeStr(),
//				cityCostRuleForMerchant, cityCostRuleForWorker);
//		Double merchantsPrice = Arith.add(Double.valueOf(priceMap.get("merchantsPrice").toString()),
//				accessoryPriceForMerchant);
//		Double indentPrice = Arith.add(Double.valueOf(priceMap.get("indentPrice").toString()), accessoryPriceForWorker);
//		Double merchantsRealPrice = Double.valueOf(priceMap.get("merchantsRealPrice").toString());
//		Double workerRealPrice = Double.valueOf(priceMap.get("workerRealPrice").toString());
//
//		if (merchantsRealPrice.compareTo(cityCostRuleForMerchant.getInstallStartingFare()) >= 0) {
//			merchantsPrice = merchantsRealPrice;
//		} else {
//			merchantsPrice = cityCostRuleForMerchant.getInstallStartingFare();
//		}
//
//		if (workerRealPrice.compareTo(cityCostRuleForWorker.getInstallStartingFare()) <= 0) {
//			indentPrice = cityCostRuleForWorker.getInstallStartingFare();
//		}
//
//		if (relievedBao == null) {
//			relievedBao = 0;
//		}
//		if (relievedBao == 1) {
//			merchantsPrice = merchantsPrice + 5;
//		}
//		// 是否需要添加取货地址
//		if (installIndent.getIsNeedTakeGoods() == 1) {
//			merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsPrice);
//			indentPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), indentPrice);
//		}
//		// 插入钱包数据 但是出于为激活状态
//		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
//		merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
//		merchantsWalletRecord.setIndentId(installIndent.getIndentId());
//		String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
//				PayMethod.ALIPAY.getIndex(), TypeOfIndent.INSTALL.getIndex());
//		merchantsWalletRecord.setOrderNo(lukebang_order_num);
//		merchantsWalletRecord.setMainMoney(merchantsPrice);
//		merchantsWalletRecord.setType(TypeOfIndent.INSTALL.getIndex());
//		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//		merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
//		request.setAttribute("lukebang_tradeno", lukebang_order_num);
//		request.setAttribute("lukebang_subject", "安装订单");
//		request.setAttribute("lukebang_total_fee", String.valueOf(totalPrice));
//		// request.setAttribute("lukebang_show_url", "0000004");
//		request.setAttribute("lukebang_body", "安装订单付款");
//		request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addInstall.htm");
//		Map<String, String> extraMap = new HashMap<String, String>();
//		extraMap.put("bussType", String.valueOf(TypeOfIndent.INSTALL.getName()));
//		extraMap.put("indent", String.valueOf(indentID));
//		extraMap.put("relievedBao", String.valueOf(relievedBao));
//		extraMap.put("addPrice", String.valueOf(addPrice));
//		extraMap.put("originalMerchantPrice", String.valueOf(merchantsPrice));
//		extraMap.put("originalIndentPrice", String.valueOf(indentPrice));
//		extraMap.put("merchantsRealPrice", String.valueOf(merchantsRealPrice));
//		extraMap.put("workerRealPrice", String.valueOf(workerRealPrice));
//		extraMap.put("crampetNumber", String.valueOf(crampetNumber));
//		extraMap.put("fourClawNumber", String.valueOf(fourClawNumber));
//		extraMap.put("motorNumber", String.valueOf(motorNumber));
//		request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
//		return false;
//	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
	public void insertGoodsThatExistIndent(Integer indentID, Good good, String finishShade, String clothShade,
			String yarnShade, String headShade, HttpServletRequest request, String fakeIndentID, HttpSession session) {
		if (good != null && indentID != null) {
			// 保存商品
			goodDAO.insertGoods(good);
			// 布纱是否安装一致
			Integer installCase = good.getInstallCase();
			// 添加成品帘
			if (good.getType() == 1) { // 成品帘
				JSONArray jsonArray = JSONArray.parseArray(finishShade);
				for (int index = 0; index < jsonArray.size(); index++) {
					JSONObject finishShadeJsonObject = jsonArray.getJSONObject(index);
					// insertSpecial(indentID, good, finishShade, clothShade,
					// yarnShade, headShade);
					inserJsonObject(index, 3, good.getGoodsId(), installCase, finishShadeJsonObject,
							CurtainType.ProductCurtain.getIndex());
				}
			} else { // 添加布艺帘
				if (clothShade != null) {
					JSONArray jsonArray = JSONArray.parseArray(clothShade);
					for (int index = 0; index < jsonArray.size(); index++) {
						JSONObject clothShadeJsonObject = jsonArray.getJSONObject(index);
						inserJsonObject(index, 0, good.getGoodsId(), installCase, clothShadeJsonObject,
								CurtainType.ClothCurtanin.getIndex());
					}
				}
				if (yarnShade != null) {
					JSONArray jsonArray = JSONArray.parseArray(yarnShade);
					for (int index = 0; index < jsonArray.size(); index++) {
						JSONObject yarnShadeJsonObject = jsonArray.getJSONObject(index);
						inserJsonObject(index, 1, good.getGoodsId(), installCase, yarnShadeJsonObject,
								CurtainType.ClothCurtanin.getIndex());
					}
				}
				if (headShade != null) {
					JSONArray jsonArray = JSONArray.parseArray(headShade);
					for (int index = 0; index < jsonArray.size(); index++) {
						JSONObject headShadeJsonObject = jsonArray.getJSONObject(index);
						inserJsonObject(index, 2, good.getGoodsId(), installCase, headShadeJsonObject,
								CurtainType.ClothCurtanin.getIndex());
					}
				}
			}
			// 绑定goodid和indentID
			Map<String, Object> param = new HashMap<>();
			param.put("indentId", indentID);
			param.put("goodsId", good.getGoodsId());
			installIndentDAO.insertGoodsIndent(param);

			// 更新价格
			// 计算商家和工人对应的配件价格
			CustomerAddress customerAddress = customerAddressDAO.selectCustomerAddressByIndent(indentID);
			if (customerAddress != null) {
				CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
						.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
				CityCostRule cityCostRuleForWorker = cityCostRuleDAO
						.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
				InstallIndent installIndent = installIndentDAO.selectByPrimaryKey(indentID);
				Map<String, Object> priceMap = calculateIndentByIndentId(installIndent,
						customerAddress.getCuAddressCodeStr(), cityCostRuleForMerchant, cityCostRuleForWorker);
				Double merchantsPrice = Double.valueOf(priceMap.get("merchantsPrice").toString());
				Double indentPrice = Double.valueOf(priceMap.get("indentPrice").toString());
				Double merchantsRealPrice = Double.valueOf(priceMap.get("merchantsRealPrice").toString());
				Double workerRealPrice = Double.valueOf(priceMap.get("workerRealPrice").toString());

				if (merchantsRealPrice.compareTo(cityCostRuleForMerchant.getInstallStartingFare()) >= 0) {
					merchantsPrice = merchantsRealPrice;
				} else {
					merchantsPrice = cityCostRuleForMerchant.getInstallStartingFare();
				}
				if (workerRealPrice.compareTo(cityCostRuleForWorker.getInstallStartingFare()) <= 0) {
					indentPrice = cityCostRuleForWorker.getInstallStartingFare();
				}

				priceMap.put("indentPrice", indentPrice);
				priceMap.put("merchantsPrice", merchantsPrice);
				priceMap.put("merchantsRealPrice", merchantsRealPrice);
				priceMap.put("workerRealPrice", workerRealPrice);
				priceMap.put("indentId", indentID);
				installIndentDAO.modifyIndentByIndentId(priceMap);
			}
		}
	}

	// 删除商品后重新计算价格
	public Map<String, Object> resetCalculateIndent(Integer indentID) {
		CustomerAddress customerAddress=new CustomerAddress();
		Indent indent=indentDao.get(indentID);
		customerAddress=customerAddressDAO.selectCustomerAddressByIndent(indentID);//根据订单id，查询customerAddress			
		// 计算商家和工人对应的配件价格
		// 计算商家和工人对应的配件价格
		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
		CityCostRule cityCostRuleForWorker = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
		// 返回值包括 indentPrice merchantsPrice realPrice
		Map<String, Object> priceMap = calculateIndentByIndentId(indent, customerAddress.getCuAddressCodeStr(),
				cityCostRuleForMerchant, cityCostRuleForWorker);
		System.out.println("***********priceMap=" + priceMap);
		Double merchantsPrice = Double.valueOf(priceMap.get("merchantsPrice").toString());
		Double indentPrice = Double.valueOf(priceMap.get("indentPrice").toString());
		Double merchantsRealPrice = Double.valueOf(priceMap.get("merchantsRealPrice").toString());
		Double workerRealPrice = Double.valueOf(priceMap.get("workerRealPrice").toString());
		if (merchantsRealPrice.compareTo(cityCostRuleForMerchant.getInstallStartingFare()) >= 0) {
			merchantsPrice = merchantsRealPrice;
		} else {
			merchantsPrice = cityCostRuleForMerchant.getInstallStartingFare();
		}

		if (workerRealPrice.compareTo(cityCostRuleForWorker.getInstallStartingFare()) <= 0) {
			indentPrice = cityCostRuleForWorker.getInstallStartingFare();
		}
		// 是否需要添加取货地址
		int isNeedTakeGoods = installIndentDAO.selectIsNeedTakeGoodsByIndentID(indentID);
		if (isNeedTakeGoods == 1) {
			merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsPrice);
			indentPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), indentPrice);
		}
		priceMap.put("indentPrice", indentPrice);
		priceMap.put("merchantsPrice", merchantsPrice);
		priceMap.put("workerRealPrice", workerRealPrice);
		priceMap.put("merchantsRealPrice", merchantsRealPrice);
		priceMap.put("indentId", indent.getIndentId());
		installIndentDAO.modifyIndentByIndentId(priceMap);

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("indentID", indent.getIndentId());
		retMap.put("price", merchantsPrice);
		retMap.put("workerRealPrice", workerRealPrice);
		retMap.put("merchantsRealPrice", merchantsRealPrice);
		return retMap;
	}

}